package com.example.service.impl;
import com.example.dao.EvaluateUserBehaviorMapper;
import com.example.dao.TransactMapper;
import com.example.microinvestcommon.entity.BuyStock;
import com.example.microinvestcommon.entity.SellStock;
import com.example.microinvestcommon.entity.UserOrder;
import com.example.microinvestcommon.pojo.Result;
import com.example.microinvestcommon.service.RedisService;
import com.example.microinvestcommon.util.SnowflakeIdGeneratorUtil;
import com.example.microinvestcommon.vo.UserOrderVo;
import com.example.service.OrderService;
import com.example.service.UserTradeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserTradeServiceImpl implements UserTradeService {

    private final EvaluateUserBehaviorMapper evaluateUserBehaviorMapper;
    private final TransactMapper transactMapper;
    private final OrderService orderService;
    private final RedisService redisService;
    private final SnowflakeIdGeneratorUtil snowflakeIdGeneratorUtil;
    private static final Logger logger = LoggerFactory.getLogger(UserTradeService.class);

    @Autowired
    UserTradeServiceImpl(EvaluateUserBehaviorMapper evaluateUserBehaviorMapper,TransactMapper transactMapper,OrderService orderService,RedisService redisService,SnowflakeIdGeneratorUtil snowflakeIdGeneratorUtil){
        this.evaluateUserBehaviorMapper=evaluateUserBehaviorMapper;
        this.transactMapper=transactMapper;
        this.orderService=orderService;
        this.redisService=redisService;
        this.snowflakeIdGeneratorUtil=snowflakeIdGeneratorUtil;
    }

    //创建购买订单交易
    @Override
    @Transactional
    public Result<String> createBuyTradeService(UserOrder userOrder,double nowPrice) {

        //判断用户余额是否充足
        if(!evaluateUserBehaviorMapper.isUserBalanceEnough(userOrder.getUserId(),userOrder.getOrderAllAmount())){
            return Result.error("您的余额不足");
        }
        //余额充足进行减少
        evaluateUserBehaviorMapper.reduceUserBalance(userOrder.getUserId(),userOrder.getOrderAllAmount());

        //创建订单
        transactMapper.addUserOrder(userOrder);
        //订单存入redis
        redisService.storeOrderId(String.valueOf(userOrder.getOrderId()),String.valueOf(userOrder.getUserId()));
        Result result=orderService.pushBuyOrderService(userOrder,nowPrice);

        return result;
    }

    //创建卖出订单交易
    @Override
    @Transactional
    public Result<String> createSellTradeService(UserOrder userOrder,double nowPrice) {

        //判断用户股票数量是否充足
        if(userOrder.getStockQuantity()>transactMapper.returnOneStockTotalQuantity(userOrder.getUserId(),userOrder.getStockSymbol())){
            return Result.error("您所持有的股票数量不足");
        }
        //股票数量充足进行减少
        transactMapper.reduceStockQuantity(userOrder.getUserId(),userOrder.getStockSymbol(),userOrder.getStockQuantity());

        //创建订单
        transactMapper.addUserOrder(userOrder);
        //订单存入redis
        redisService.storeOrderId(String.valueOf(userOrder.getOrderId()),String.valueOf(userOrder.getUserId()));
        Result result=orderService.pushSellOrderService(userOrder,nowPrice);

        return result;
    }

    //写入购买全部记录
    @Override
    @Transactional
    public void addBuyTradeService(UserOrder userOrder) {

        //更新用户购买的股票数据
        Boolean isUserBuyThisStock = evaluateUserBehaviorMapper.isUserBuyThisStock(userOrder.getUserId(), userOrder.getStockSymbol());
        if (!isUserBuyThisStock) {
            // 如果用户没有购买过此股票，则初始化该股票数据
            evaluateUserBehaviorMapper.addStockToUser(userOrder.getUserId(), userOrder.getStockSymbol());
        }

        //添加用户购买的总amount
        transactMapper.addUserTotalAmount(userOrder.getStockSymbol(),userOrder.getOrderAllAmount());

        //增加用户持有股票数量
        transactMapper.addStockQuantity(userOrder.getUserId(), userOrder.getStockSymbol(), userOrder.getStockQuantity());

        //初始化buystock
        BuyStock buyStock=new BuyStock(userOrder.getUserId(),userOrder.getStockSymbol(),userOrder.getOrderAmount(),userOrder.getStockQuantity(),snowflakeIdGeneratorUtil);

        //添加购买记录（更新购买信息）
        transactMapper.addUserBuyStock(buyStock);

        logger.info("写入购买记录成功:{}",userOrder);
    }

    //写入卖出全部记录
    @Override
    @Transactional
    public void addSellTradeService(UserOrder userOrder) {


        //减少用户购买的总amount
        transactMapper.reduceUserTotalAmount(userOrder.getStockSymbol(),userOrder.getOrderAllAmount());

        //增加用户余额
        evaluateUserBehaviorMapper.addUserBalance(userOrder.getUserId(),userOrder.getOrderAllAmount());

        //初始化sellStock
        SellStock sellStock =new SellStock(userOrder.getUserId(),userOrder.getStockSymbol(),userOrder.getOrderAmount(),userOrder.getStockQuantity(),snowflakeIdGeneratorUtil);

        //添加购买记录（更新购买信息）
        transactMapper.addUserSellStock(sellStock);

        logger.info("写入卖出记录成功:{}",userOrder);

    }

}
